package com.maserb.monitor.remote;


import org.apache.commons.lang3.ArrayUtils;
import org.apache.poi.util.ArrayUtil;

public class MessageByteUtils {
    public static byte[] fromString(String str, int length) {
        if (str == null) {
            return new byte[0];
        }
        byte[] result = new byte[length];
        byte[] bytes = str.getBytes();
        int diffLength = result.length - bytes.length;
        diffLength = diffLength < 0 ? 0 : diffLength;
        for (int i = 0; i < bytes.length; i++) {
            result[diffLength + i] = bytes[i];
        }
        return result;
    }

    public static String getString(byte[] data) {
        try {
            int length = data.length;
            for (int i = 0; i < data.length; ++i) {
                if (data[i] == 0) {
                    length = i;
                    break;
                }
            }
            String result = new String(data, 0, length).replaceAll(" ", "");
            return result;
        } catch (Exception e) {
            return "";
        }
    }

    public static byte[] fromInt(int a) {
        return new byte[]{
                (byte) ((a >> 24) & 0xFF),
                (byte) ((a >> 16) & 0xFF),
                (byte) ((a >> 8) & 0xFF),
                (byte) (a & 0xFF)
        };
    }

    public static int getInt(byte[] b) {
        return b[3] & 0xFF |
                (b[2] & 0xFF) << 8 |
                (b[1] & 0xFF) << 16 |
                (b[0] & 0xFF) << 24;
    }
}